import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/base/PageProvideNode.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/home/HomeAttentionBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/home/HomeAttentionPageBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/AccidentTreatment.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ImageHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/SmartRefresherHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ViewHelper.dart';

import 'HomeVM.dart';

//关注
var vmAttention = HomeVM();

class Attention extends StatefulWidget {

  @override
  _AttentionState createState() => _AttentionState();
}

class _AttentionState extends State<Attention> with AutomaticKeepAliveClientMixin {

  PullDataRefresher<AttentionPageBean> mPullDataRefresher=PullDataRefresher(null);

  late LoadCallback mLoadCallback;

  @override
  void initState() {
    super.initState();
    mLoadCallback=(pullBean){
      if(pullBean.pageNum==1){
        //关注的店铺
        vmAttention.getAttention(isDialog: false);
      }
      vmAttention.getAttentionList(pullBean,requestDone: (){
        //关注的店铺 的信息
         mPullDataRefresher.onRefresher(vmAttention.attentionPageBeans);
      },isDialog: false);
    };
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      child: SmartRefresherWidget<AttentionPageBean>(
        controller: RefreshController(),
        enablePullDown: true,
        enablePullUp: true,
        valueNotifier:mPullDataRefresher,
        onLoading: mLoadCallback,
        onRefresh: mLoadCallback,
        loadBuild: (BuildContext context,List<AttentionPageBean> result){
          return CustomScrollView(
              slivers: [
                SliverToBoxAdapter(
                  child: Column(
                    children: [
                      SearchWidget(),
                      OftenVisit(),
                    ],
                  ),
                ),
                SliverList(delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index){
                        return AttentionItem(result[index]);
                    },
                    childCount:result.length,
                ),
                )
              ],
          );
        },
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

}

//搜索栏w
class SearchWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
        color: Colors.white,
        padding: EdgeInsets.fromLTRB(12.w, 2.h, 12.w, 2.h),
        child: Row(
          children: [
            //扫一扫
            Container(
              width: 33.w,
              height: 35.w,
              alignment: Alignment.center,
              margin: EdgeInsets.fromLTRB(0.w, 0, 10.w, 0),
              child: TextButton(
                style: ButtonStyle(
                    minimumSize: MaterialStateProperty.all(Size(0, 0)),
                    padding: MaterialStateProperty.all(EdgeInsets.fromLTRB(0, 0, 0.w, 0))),
                onPressed: () {},
                child: Column(
                  children: [
                    Image.asset(assetPath("ic_home_btn_scan.png"),
                      width: 20.w,
                      height: 20.w,
                      color: Color(0xff9A9BA4),
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 2, 0, 0),
                      child: Text("扫一扫", style:TextStyle(fontSize: 10.sp,color: Color(0xff9A9BA4) ),textAlign: TextAlign.end),
                    )
                  ],
                ),
              ),
            ),
            //搜索框
            Expanded(
              child: TextButton(
                onPressed: () {},
                child: Padding(
                  padding: EdgeInsets.fromLTRB(4.w, 0, 4.w, 0),
                  child: Row(
                    children: [
                      Expanded(child: Text("搜索产品", style: TextStyle(fontSize: 14.sp, color: Color(0xffBFC1CD),),),),
                      Image.asset(assetPath("ic_search_btn_gray.png"), width: 14.w, height: 14.h,color: Color(0xff9A9BA4),)
                    ],
                  ),
                ),
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Color(0xffF4F6F8)),
                    shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.horizontal(left: Radius.circular(24.r), right: Radius.circular(24.r))))),
              ),
            ),
            //图搜布
            Container(
              width: 33.w,
              height: 35.w,
              alignment: Alignment.center,
              margin: EdgeInsets.fromLTRB(10.w, 0, 0.w, 0),
              child: TextButton(
                style: ButtonStyle(
                    minimumSize: MaterialStateProperty.all(Size(0, 0)),
                    padding: MaterialStateProperty.all(EdgeInsets.fromLTRB(0, 0, 0.w, 0))),
                onPressed: () {},
                child: Column(
                  children: [
                    Image.asset(assetPath("ic_photo_white.png"),
                      width: 20.w,
                      height: 20.w,
                      color: Color(0xff9A9BA4),
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 2, 0, 0),
                      child: Text("图搜布", style:TextStyle(fontSize: 10.sp,color: Color(0xff9A9BA4) ),textAlign: TextAlign.end,),
                    )
                  ],
                ),
              ),
            ),
          ],
        ));
  }
}

//常访问的
class OftenVisit extends PageProvideNode {

  OftenVisit() : super(vmAttention);

  @override
  Widget buildContent(BuildContext context) {
    var size = MediaQuery.of(context).size;
     return Container(
       decoration: BoxDecoration(
           color: Colors.white,
           borderRadius: BorderRadius.only(bottomLeft:Radius.circular(16),bottomRight: Radius.circular(16) )),
      margin: EdgeInsets.fromLTRB(0, 1.h, 0, 6.h),
      padding: EdgeInsets.fromLTRB(12.w, 10.h, 12.w, 15.h),
      child: ChangeNotifierProvider(
        create: (BuildContext context) {
           return vmAttention;
        },
        child: Selector(
          builder: (context,HomeAttentionBean? value,child) {
             List<FrequentlyViewList>? list=value?.frequentlyViewList;
             if(list==null || list.isEmpty!=false){ //空数据展示
                return Container(width:size.width,height:80.h,child:Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("您还没有关注的账号哦 ~",style: TextStyle(fontSize: 16.sp,color: Color(0xff333333),height: 2),),
                    Text("为您推荐了有趣的账号快去关注吧",style: TextStyle(fontSize: 13.sp,color: Color(0xff999999),),),
                  ],),alignment: Alignment.center,);
             }else{
               return Column(
                 children: [
                   Row(
                     children: [
                       Expanded(child: Text("常访问的",style: TextStyle(color: Color(0xff333333),fontSize: 16.sp,fontWeight: FontWeight.w700),)),
                       Text("更多",style: TextStyle(color: Color(0xff333333),fontSize: 13.sp,fontWeight: FontWeight.w600),),
                     ],
                   ),
                   Container(
                     margin:EdgeInsets.fromLTRB(0.w, 20.h, 0.w, 0.h),
                     height:(size.width-24-4*10)/5+40.h,
                     child: ListView.separated(
                        itemCount: list.length,
                        scrollDirection: Axis.horizontal,
                        itemBuilder: (BuildContext context, int index){
                          FrequentlyViewList item = list[index];
                          return OftenVisitItem(index,item);
                     }, separatorBuilder: (BuildContext context, int index) {
                          return Divider(color: Colors.transparent, indent: 10,);
                     },),
                   ),
                 ],
               );
             }
          },
          selector: (BuildContext , HomeVM homeVm ) {
              return vmAttention.attentionBean;
          },
        ),
      ),
    );
  }
}

//常访问的Item
class OftenVisitItem extends StatelessWidget {

  int index;
  FrequentlyViewList item;

  OftenVisitItem(this.index, this.item);

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    double imageWidth=(size.width-24)/5;
    return Container(
        width: imageWidth,
        child: Column(
          children: [
            ClipRRect(borderRadius: BorderRadius.all(Radius.circular(4.r)), child:assetImage("${item.storeLogo}", width: imageWidth,height:imageWidth),),
            Padding(padding: EdgeInsets.fromLTRB(0, 7.h, 0, 7.h),
              child: Text("${item.storeName}",style: TextStyle(color: Color(0xff666666),fontSize: 12.sp),softWrap: true,overflow: TextOverflow.ellipsis,maxLines: 1,),
            )
          ],
        ),
    );
  }
}

//动态Item
class AttentionItem extends StatelessWidget {

  AttentionPageBean attentionPageBean;

  AttentionItem(this.attentionPageBean);

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    var imageWidth = (size.width-24-18-16)/3;
    var len = attentionPageBean.pic?.length??0;
    var allHeight=calculateHeight(imageWidth, len,1);
    return Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(GenericViewParameters.bgRoundedCorners))),
         margin: EdgeInsets.fromLTRB(12.w, 6.w, 12.w, 6.w),
         padding: EdgeInsets.all(8.w),
         child: Column(
           children: [
             ListStoreTitle(imageUrl: attentionPageBean.storeLogo??"", storeName: attentionPageBean.storeName??"--", describeName: attentionPageBean.time??""),
             ShowDynamicText(checkNullOrEmpty(attentionPageBean.introduce,"-没有文字评价-"),attentionPageBean.type??1),
             Container(
               height: allHeight+10.h,
               child: GridView.builder(
                   scrollDirection: Axis.vertical,
                   padding: EdgeInsets.fromLTRB(0, 10.h, 0, 0),
                   physics: NeverScrollableScrollPhysics(),
                   itemCount: attentionPageBean.pic?.length??0,
                   gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3,mainAxisSpacing: 9.w,crossAxisSpacing: 9.w),
                   itemBuilder: (BuildContext context, int index){
                      return DufRoundedWidget(assetImage(attentionPageBean.pic?[index]??"",width: imageWidth,height: imageWidth,fit: BoxFit.fill));
                   }),
             ),
             Visibility(
                 visible: (attentionPageBean.type??0)==1,
                 child: Padding(
                   padding:  EdgeInsets.fromLTRB(0, 8.h, 0, 0),
                   child: GoodsHTitle(imageUrl: attentionPageBean.productPic??"", goodsName: attentionPageBean.productName??"", priceText: "${attentionPageBean.productPrice??"--"}", unitText: attentionPageBean.unit??""),
                 ))
           ],
         ),
       );
  }
}

//动态 text
class ShowDynamicText extends StatelessWidget{

  String text;
  int type;
  ShowDynamicText(this.text,this.type);

  @override
  Widget build(BuildContext context) {
      return Container(
        margin: EdgeInsets.fromLTRB(0, 15.h, 0, 6.h),
        padding: EdgeInsets.fromLTRB(3, 0, 0, 0),
        alignment: Alignment.centerLeft,
        child: Stack(
          children: [
            tabDynamic(type),
            Text("\u3000\u3000\u3000\u0020\u0020${text}",style: TextStyle(color: Color(0xff333333),fontSize: 15.sp,height: 1.8,),maxLines: 6,),
          ],
        ),
      );
  }

}

//动态标签
Widget tabDynamic(int type){
  if(type==1){
    return Container(
      width:42.w ,
      height: 18.h,
      margin: EdgeInsets.fromLTRB(0, 8.sp, 0, 0),
      padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(3)),
          gradient: LinearGradient(colors: [Color(0xffFFAD4C),Color(0xffFFCD6C)],begin: Alignment.topCenter,end: Alignment.bottomCenter)
      ),
      child: SizedBox(height:double.infinity,child: Text("买家秀",style: TextStyle(color: Colors.white,fontSize: 12.sp),textAlign: TextAlign.center,)),
    );
  }else{
    return Container(
      width:42.w ,
      height: 18.h,
      margin: EdgeInsets.fromLTRB(0, 8.sp, 0, 0),
      padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(3)),
          gradient: LinearGradient(colors: [Color(0xff3AD888),Color(0xff7CF0AD)],begin: Alignment.topCenter,end: Alignment.bottomCenter)
      ),
      child: SizedBox(height:double.infinity,child: Text("上新",style: TextStyle(color: Colors.white,fontSize: 12.sp),textAlign: TextAlign.center,)),
    );
  }
}

